

<template>
  <view class="Mall4j">
    <!-- 拼团详情 -->
    <!-- pages/SpellGroupDetails/spell-group-details.wxml -->
    <view v-if="groupTempInfo.groupTeam" class="top-box" :style="isEn? 'height: unset' : ''">
      <view class="top-bg" />
      <!-- 商品内容盒子 -->
      <view class="goods-content">
        <view class="goods-img-box">
          <image :src="groupTempInfo.groupProd.prodPic" class="goods-img" />
        </view>
        <!-- 商品信息信息 -->
        <view class="goods-msg">
          <text class="goods-title">{{ groupTempInfo.groupProd.prodName }}</text>
          <!-- 商品规格 -->
          <!-- <view class="goods-sku">{{groupTempInfo.groupProd.skuName}}</view> -->
          <!-- 价格 -->
          <view class="goods-price">
            <text class="spell-group-price">￥{{ groupTempInfo.groupProd.actPrice }}</text>
            <text class="original-price">￥{{ groupTempInfo.groupProd.price }}</text>
          </view>
        </view>
      </view>
      <!-- 商品内容盒子 end -->
      <!-- 规则 -->
      <view class="tips-text clearfix">
        <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/thumb.png" class="thumb-icon" />
        <view class="tips-text-cnt">{{ i18n.groupJoiningRules1 }} {{ joinNum }} {{ i18n.groupJoiningRules2 }}</view>
        <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/more.png" class="right-arrow-icon" />
      </view>
    </view>
    <!-- 下 -->
    <view v-if="groupTempInfo.groupTeam" class="condition">
      <!-- 剩余时间 -->
      <view class="time-remaining">
        <text class="line-left" />
        <text v-if="groupTempInfo.groupTeam.status == 1 && !isEnd" class="time-text">{{ i18n.groupJoinTime }}</text>
        <text v-if="groupTempInfo.groupTeam.status == 2" class="time-text">{{ i18n.groupJoiningSuccess }}</text>
        <text v-if="groupTempInfo.groupTeam.status == 3 || isEnd" class="time-text">{{ i18n.groupJoiningFailure }}</text>
        <text class="line-right" />
      </view>
      <view v-if="groupTempInfo.groupTeam.status == 1 && !isEnd" class="countdown">
        <text class="time-number">{{ countDownObj.hou }}</text>：<text class="time-number">{{ countDownObj.min }}</text>：<text class="time-number">{{ countDownObj.sec }}</text>
      </view>

      <!-- 人员 -->
      <view class="member" :style="'padding-left:' + (groupUserList.length>4? '40px;': (groupUserList.length-2) * 10 + 'px;')">
        <block v-for="(groupUser, index) in groupUserList" :key="index">
          <view v-if="groupUser.identityType == 1" class="captain">
            <image v-if="groupUser.pic" class="captain-img" :src="groupUser.pic" />
            <image v-else class="captain-img" src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/head04.png" />
            <text class="status">{{ i18n.teamLeader }}</text>
          </view>
          <view v-else-if="groupUser.identityType == 0 && index<5" class="group-member" :style="'z-index:' + ((-index+99)) + '; left:' + (-index*10) + 'px'">
            <image class="group-member-img" :src="groupUser.pic" />
          </view>
          <view v-else class="group-member" :style="'z-index:' + ((-index+99)) + '; left:' + (-index*10) + 'px'">
            <image class="group-member-img" src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/head04.png" />
          </view>
        </block>
      </view>
      <view v-if="groupTempInfo.groupTeam.groupNumber> 5" class="more-ellipsis">
        <text decode="true">·&nbsp;·&nbsp;·</text>
      </view>

      <!-- 查看全部团员btn -->
      <view class="view-all display">{{ i18n.viewAllMembers }}</view>
      <view v-if="groupTempInfo.groupTeam.status == 1 && !isEnd" class="invite-text">{{ i18n.onlyLeft }}<text>{{ groupTempInfo.groupTeam.groupNumber - groupTempInfo.groupTeam.joinNum }}</text>{{ i18n.peopleJoinGroup }}</view>
      <view class="invite-text  display">{{ i18n.lack }}<text>{{ groupTempInfo.groupTeam.groupNumber - groupTempInfo.groupTeam.joinNum }}</text>{{ i18n.peopleGroupSuccess }}</view>
      <!-- 邀请好友参团 -->
      <!-- #ifdef H5 -->
      <view v-if="groupTempInfo.groupTeam.status == 1 && !isEnd" class="join-now" @tap="h5Share">{{ i18n.inviteFriendsJoin }}</view>
      <!-- #endif -->
      <!-- #ifdef MP -->
      <button v-if="groupTempInfo.groupTeam.status == 1 && !isEnd" class="join-now" open-type="share">{{ i18n.inviteFriendsJoin }}</button>
      <!-- #endif -->
      <!-- 立即参团btn   wx:if="{{groupTempInfo.groupTeam.status == 1 && groupTempInfo.orderNumber}}"-->
      <view v-if="!groupTempInfo.orderNumber && groupTempInfo.groupTeam.status == 1 && !isEnd" class="join-now" @tap="showSku">{{ i18n.JoinGroupNow }}</view>
      <!-- 查看团队 -->
      <view class="join-now" :data-groupteamid="groupTempInfo.groupTeam.groupTeamId" @tap="toGroupTempInfoPage">{{ i18n.viewTeam }}</view>
      <!-- 查看详情btn -->
      <view v-if="groupTempInfo.orderNumber" :data-ordernum="groupTempInfo.orderNumber" class="check-order" @tap="toOrderDetailPage">{{ i18n.viewOrderDetails }}</view>
      <!-- 商城首页按钮: 扫码进入的时候无法返回上一页 -->
      <view v-if="showIndexBtn" class="check-order" @tap="toIndex"> {{ i18n.backHomepage }} </view>
    </view>

    <!-- 规格弹窗 -->
    <prod-sku-select v-if="skuShow" :pic="groupTempInfo.groupProd.prodPic" :sku-list="groupTempInfo.groupSkuList" :default-price="groupTempInfo.groupProd.actPrice" :sku-show-type="1" :prod-type="1" :prod-num="prodNum" :page-type="0" :sku-show="skuShow" :is-jion-group="true" @groupConfirmOrder="groupConfirmOrder" @setSku="setSku" @closeSkuPop="closePopup" @setProdNum="setProdNum" />
    <!-- 规格弹窗 end -->

    <!-- 引导分享蒙版 -->
    <guide-share v-if="showGuideShare" :is-wechat="isWechat" :qr-link="qrLink" @hideGuideShare="hideGuideShare" />
    <!-- 引导分享蒙版 end -->
  </view>
</template>

<script module="wxs" lang="wxs" src="../../../wxs/number.wxs"></script>

<script>
// pages/spell-group-details/spell-group-details.js
var http = require("../../../utils/http.js");
var config = require("../../../utils/config.js");
var util = require("../../../utils/util.js");
import Wechat from "../../../utils/wechat.js";
import guideShare from '../../../components/guide-share/index.vue';
import prodSkuSelect from '@/components/prod-sku-select/index.vue';

export default {
  data () {
    return {
      hideModal: true,
      groupTempInfo: {},
      groupUserList: [],
      countDownObj: {},
      countDownTimeout: null,
      nowTime: new Date().getTime(),
      skuShow: false,
      prodNum: 1,
      skuList: [],
      findSku: true,
      defaultSku: undefined,
      groupTeamId: '',
      groupSkuId: 0,
      joinNum: "",
      isEnd: false, // 当前拼团是否已经结束
      isEn: uni.getStorageSync('lang') == 'en' ? true : false, // 是否为英文
      showGuideShare: false, // 分享引导显隐
      isWechat: false, // 是否微信环境
      showQr: false, // H5 二维码显隐
      qrLink: '', // H5二维码地址
      orderNumber: '',
      showIndexBtn: false
    };
  },

  components: {
    guideShare,
    prodSkuSelect
  },
  computed: {
    i18n () {
      return this.$t('index')
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // #ifdef H5
    this.isWechat = Wechat.isWechat()
    // #endif
    let groupTeamId = this.$Route.query.groupTeamId || '';
    let orderNumber = this.$Route.query.orderNumber || ''
    this.setData({
      orderNumber: orderNumber,
      groupTeamId: groupTeamId
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //头部导航标题
    uni.setNavigationBarTitle({
      title: this.i18n.groupDetails
    });
    this.getGroupTeamInfo(this.groupTeamId, this.orderNumber)
    console.log(getCurrentPages().length);
    this.showIndexBtn = getCurrentPages().length === 1
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearTimeout(this.countDownTimeout);
    this.closePopup()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () { },

  /**
   * 小程序: 邀请好友参团
   */
  onShareAppMessage: function (res) {
    return {
      title: this.groupTempInfo.groupProd.prodName,
      path: '/package-activities/pages/spell-group-details/spell-group-details?groupTeamId=' + this.groupTeamId,
      imageUrl: this.groupTempInfo.groupProd.prodPic
    };
  },
  methods: {

    /**
     * 修改商品的sku
     */
    setSku (sku, findSku) {
      this.findSku = findSku
      this.defaultSku = sku
    },

    /**
     * 修改商品数量
     */
    setProdNum (prodNum) {
      this.prodNum = prodNum
    },

    /**
     * 返回首页
     */
    toIndex () {
      this.$Router.pushTab('/pages/index/index')
    },

    /**
     * 输入商品数量
     */
    prodNumInp (e) {
      let num = Number(e.detail.value.replace(/[^\d]/g, ''))
      this.prodNum = num
    },
    /**
     * H5: 邀请好友参团
     */
    h5Share () {
      let link = `${config.domainAddress}/package-activities/pages/spell-group-details/spell-group-details?groupTeamId=${this.groupTeamId}`
      if (this.isWechat) {
        // 微信内部浏览器
        var sharedata = {
          title: this.groupTempInfo.groupProd.prodName, // 分享标题
          imgUrl: this.groupTempInfo.groupProd.prodPic, // 分享图标
          link: link,
          desc: this.i18n.shartTips, // 分享描述
          type: '', // 分享类型,music、video或link，不填默认为link
          dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
        };
        Wechat.callWexinShare(sharedata, () => {
          this.showGuideShare = true
        }, (failMsg) => {
          console.log(failMsg)
        })
      } else {
        // 普通H5浏览器: 显示生成的二维码
        this.qrLink = link
        this.showGuideShare = true
      }
    },
    /**
     * 关闭分享引导
     */
    hideGuideShare (e) {
      this.showGuideShare = e
    },

    /**
     * 参团
     */
    groupConfirmOrder: function () {
      if (!this.findSku) {
        return;
      }
      if (this.prodNum < 1) {
        uni.showToast({
          title: this.i18n.leastTips,
          icon: 'none'
        })
        this.prodNum = 1
        return
      }
      uni.setStorageSync("groupOrderItem", JSON.stringify({
        groupSkuId: this.defaultSku.groupSkuId,
        groupTeamId: this.groupTeamId,
        prodCount: this.prodNum
      }));
      uni.navigateTo({
        url: '/package-activities/pages/group-confirm-order/group-confirm-order'
      });
    },

    // 提交订单
    commitOrder () {
      var orderShopParam = {
        remarks: ""
      };
      http.request({
        url: `/p/group/order/submit`,
        method: 'POST',
        data: orderShopParam,
        callBack: res => {
          this.calWeixinPay(res.orderNumbers);
        }
      });
    },

    /**
     * 唤起微信支付
     */
    calWeixinPay: function (orderNumbers) {
      var params = {
        url: "/p/order/pay",
        method: "POST",
        data: {
          payType: 1,
          orderType: 1,
          orderNumbers: orderNumbers
        },
        callBack: res => {
          uni.requestPayment({
            timeStamp: res.timeStamp,
            nonceStr: res.nonceStr,
            package: res.packageValue,
            signType: res.signType,
            paySign: res.paySign,
            success: e => {
              uni.showModal({
                title: this.i18n.paymentSuccessful,
                content: '',
                showCancel: false,
                success: () => {
                  uni.navigateTo({
                    url: '/package-activities/pages/spell-group-details/spell-group-details?orderNumber=' + orderNumbers
                  });
                }
              });
            },
            fail: err => {
              uni.navigateTo({
                url: '/pages/pay-result/pay-result?sts=0&orderNumbers=' + orderNumbers + "&orderType=" + this.orderType
              });
            }
          });
        }
      };
      http.request(params);
    },

    /**
     * 去地址页面
     */
    toAddrListPage: function () {
      uni.navigateTo({
        url: '/pages/delivery-address/delivery-address?order=0'
      });
    },
    showSku: function () {
      this.setData({
        skuShow: true
      });
    },
    closePopup: function () {
      this.setData({
        skuShow: false
      });
    },

    /**
     * 加载拼团团队详情
     */
    getGroupTeamInfo (groupTempId, orderNumber) {
      http.request({
        url: "/p/groupTeam/info",
        method: "GET",
        data: {
          groupTeamId: groupTempId,
          orderNumber: orderNumber
        },
        callBack: res => {
          this.skuList = res.groupSkuList
          this.groupTempInfo = res
          this.groupUserList = res.apiGroupUserList
          this.nowTime = util.dateToTimestamp(res.groupTeam.nowTime)
          this.joinNum = res.groupTeam.groupNumber - 1
          this.groupTeamId = res.groupTeam.groupTeamId

          let groupUserCount = this.groupUserList.length > 5 ? 5 : this.groupUserList.length;
          let groupNumber = this.groupTempInfo.groupTeam.groupNumber > 5 ? 5 : this.groupTempInfo.groupTeam.groupNumber;
          let unGroupNumber = groupNumber - groupUserCount;
          let groupUserList = this.groupUserList;
          if (unGroupNumber > 0) {
            for (let i = 0; i < unGroupNumber; i++) {
              groupUserList = groupUserList.concat({});
            }
          }
          this.groupUserList = groupUserList
          if (res.groupTeam.status == 2) {
            // 拼团已经结束
            return
          }
          this.countdown()
        }
      });
    },

    // 倒计时
    countdown () {
      // 获取当前时间，同时得到活动结束时间数组
      let nowTime = this.nowTime;
      let endTime = util.dateToTimestamp(this.groupTempInfo.groupTeam.endTime);
      let countDownObj = {}; // 对结束时间进行处理渲染到页

      if (endTime - nowTime > 0) {
        // 如果活动未结束，对时间进行处理
        let time = (endTime - nowTime) / 1000; // 获取天、时、分、秒

        let day = parseInt(time / (60 * 60 * 24));
        let hou = parseInt(time % (60 * 60 * 24) / 3600);
        let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
        let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
        countDownObj = {
          day: `${this.timeFormat(day)}`,
          hou: `${this.timeFormat(hou)}`,
          min: `${this.timeFormat(min)}`,
          sec: `${this.timeFormat(sec)}`
        };
      } else {
        countDownObj = {
          day: '00',
          hou: '00',
          min: '00',
          sec: '00'
        };
        this.isEnd = true
        this.groupTempInfo.groupTeam.status = 3
        clearTimeout(this.countDownTimeout);
      } // 渲染，然后每隔一秒执行一次倒计时函数

      this.setData({
        nowTime: nowTime + 1000,
        countDownObj: countDownObj,
        countDownTimeout: setTimeout(this.countdown, 1000)
      });
    },

    // 小于10的格式化函数
    timeFormat (times) {
      return times < 10 ? '0' + times : times;
    },

    /**
     * 查看订单详情
     */
    toOrderDetailPage: function (e) {
      this.$Router.replace({
        path: '/pages/order-detail/order-detail',
        query: {
          orderNum: e.currentTarget.dataset.ordernum
        }
      })
    },

    /**
     * 查看拼团团队
     */
    toGroupTempInfoPage: function (e) {
      uni.navigateTo({
        url: '/package-activities/pages/spell-members-details/spell-members-details?groupTeamId=' + e.currentTarget.dataset.groupteamid
      });
    }
  }
};
</script>
<style>
@import "./spell-group-details.css";
</style>
